// Author: simon (ynwdlxm@163.com)
// Date: 2025/5/28 16:26
// Desc:

package cmd

import (
	"github.com/spf13/cobra"

	"github.com/runningwater/gohub/database/migrations"
	"github.com/runningwater/gohub/pkg/migrate"
)

var CmdMigrate = &cobra.Command{
	Use:   "migrate",
	Short: "Run database migrations",
}

var CmdMigrateUp = &cobra.Command{
	Use:   "up",
	Short: "Run up migrations",
	Run:   runUp,
}

var CmdMigrateRollback = &cobra.Command{
	Use:     "down",
	Aliases: []string{"rollback"},
	Short:   "Run rollback migrations",
	Run:     runDown,
}

var CmdMigrateReset = &cobra.Command{
	Use:   "reset",
	Short: "Reset and re-run all migrations",
	Run: func(cmd *cobra.Command, args []string) {
		migrator().Reset()
	},
}

var CmdMigrateRefresh = &cobra.Command{
	Use:   "refresh",
	Short: "Drop all tables and re-run all migrations",
	Run: func(cmd *cobra.Command, args []string) {
		migrator().Refresh()
	},
}

var CmdMigrateFresh = &cobra.Command{
	Use:   "fresh",
	Short: "Drop all tables and re-run all migrations",
	Run: func(cmd *cobra.Command, args []string) {
		migrator().Fresh()
	},
}

// 初始化命令
func init() {
	CmdMigrate.AddCommand(
		CmdMigrateUp,
		CmdMigrateRollback,
		CmdMigrateReset,
		CmdMigrateRefresh,
		CmdMigrateFresh,
	)
}

func runUp(cmd *cobra.Command, args []string) {
	migrator().Up()
}
func runDown(cmd *cobra.Command, args []string) {
	migrator().Rollback()
}

func migrator() *migrate.Migrator {
	// 注册 database/migrations 目录下的所有迁移文件
	migrations.Initialize()

	return migrate.NewMigrator()
}
